"use strict";

import Vue from "vue";
import axios from "axios";
import Util from "../Logic/Util.js";
import Api from "../api/Userapi.js";
import store from "../store/index.js";
import router from "../router/index.js";
// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  baseURL: "http://192.168.0.2:8088/"
  // baseURL: "http://106.14.183.14:8088/"
  // baseURL: "http://192.168.0.127:8088/"
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function(config) {
    //如果vuex中存在token
    if (config.url === Api.login) {
      return config;
    }
    if (store.state.token) {
      let vali = Util.checkValid(store.state.userInfo.exp);
      if (vali) {
        config.headers.Authorization = `Bearer ${store.state.token}`;
      } else {
        router.push({
          name: "login"
        });
      }
    }
    // store.state.token;
    //store.commit('resetToken',token);
    //store.commit('clearToken',token);
    // config.headers.Authorization =  `Bearer ${store.state.token}`;
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    // Do something with response data
    // window.console.log(response);
    if (response.data.status === 1 && response.data.msg === "token无效") {
      store.commit("clearToken");
      router.push({
        name: "login"
      });
    }
    return response;
  },
  function(error) {
    // Do something with response error
    return Promise.reject(error);
  }
);

Plugin.install = function(Vue, options) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    }
  });
};

Vue.use(Plugin);

export default Plugin;
